#!/bin/sh
#set -x
BNI_USER=bninet
BNI_HOME=/home/$BNI_USER

FUNCTIONS_SRC_PATH=../../prodinstall/product-common/src/main/prodhome/bin/
FUNCTIONS=commonLib.sh
RUNTIME=commonRuntime.sh

# Source funcions
deploy_vars=`echo $* |grep '\-d'`
echo "deploy_vars=$deploy_vars"
if [[ -z $deploy_vars ]]
then
  . ./$RUNTIME
else
  . ./$FUNCTIONS
fi

# STATIC ARGS
PROGNAME=`basename $0`
LOG=./$PROGNAME.log

TMP_LOGS=/tmp/*.log
INIT_DIR=/etc/init.d
BNI_USER=bninet
BNI_HOME=/home/bninet
BNI=$BNI_HOME/bni
SPLUNK=$BNI_HOME/splunk
JBOSS_HOME=$BNI_HOME/jbossesb
BNI_DEPLOYABLES=$BNI_HOME/jbossesb/bni-deployables
BNI_DEPLOYED=$BNI_HOME/jbossesb/bni-deployed
BNI_CONF_DIR=$JBOSS_HOME/server/default/conf/bni
DEPLOY_DIR=$JBOSS_HOME/server/default/deploy
SM_NAME=CATV_SM
DB_TYPE=m
SM_NODE_NAME=`hostname`
SM_NODE_IP=`/sbin/ifconfig eth0|tr '\n' ' '|awk '{print $7}'|sed -e 's?\(^.*:\)\(.*$\)?\2?'`

# Other script dirs
AUTODEPLOY_DIR=validation/autodeploy
ANNA_CONFIGURE_DB=configure_annapurna.sh
INTERNAL_DIR=internal
INTERNAL_CATV_SCRIPTS=$INTERNAL_DIR/CatvScripts
CLUSTER_FILE=$BNI_CONF_DIR/cluster.xml

# Commands
TAR="tar -xzf"
WGET="wget -q"
RM="rm -f"
CP="cp -f"


print_help()
{
  echo "Usage $PROGNAME OPTIONS REQUIRED_ARGS"

  cat - <<EOF
where OPTIONS can be:
  -h|-H|--help  Prints (this) help message and exits
  -deploy       Deploys Annapurna to Specified SM Host
  -X            Prints what operations would be executed, but does not execute them
  -jobPrefix    Used when we have branched build
and REQUIRED_ARGS are
  -hq_port VAL  : VAL = HornetQ cluster UDP Port number
  -ss_port VAL  : VAL = Session cluster UDP Port number
  -sm           : VAL = IP address of the SM node
  -sim          : VAL = IP address of the Sim node
  -msvc         : VAL = IP address of the Management node
  -version      : VAL = Product Version
EOF
  exit 0
}
                      
clean() 
{
  if [ ! -z "$NO_EXEC" ]; then
    info "Skipping Operation: 'Clean'"
    info "Skipping Operation: $RM    $ANNA_TAR_FILE"
    info "Skipping Operation: $RM    $ANNA_PC_TAR_FILE"
    info "Skipping Operation: $RM -r $BNI"
    info "Skipping Operation: $RM -r $JBOSS_HOME"
    info "Skipping Operation: $RM -r $SPLUNK"
    info "Skipping Operation: $RM -r $INTERNAL_DIR"
    info "Skipping Operation: $RM    $TMP_LOGS"
  else
    $RM    $ANNA_TAR_FILE
    $RM    $ANNA_PC_TAR_FILE
    $RM -r $BNI
    $RM -r $JBOSS_HOME
    $RM -r $SPLUNK
    $RM -r $INTERNAL_DIR
    $RM    $TMP_LOGS
  fi
}

is_jboss_started()
{
  result=`/etc/init.d/jboss status`

  if [ "$result" = "JBOSS is already running!" ]; then
    echo "is running"
    return 1
 else
    echo "is NOT running"
    return 0
  fi
}
is_jboss_operational()
{
  if [ ! -z "$NO_EXEC" ]; then
    info "Skipping Operation: 'is_jboss_operational'"
  else
    result=`$JBOSS_HOME/bin/twiddle.sh get "jboss.system:type=Server" Started | sed -e 's/Started=//'`
	  if [ "$result" = "true" ]; then
	  	return 0
    else
      return 1
	  fi
  fi
}

start_jboss()
{
  if [ ! -z "$NO_EXEC" ]; then
    info "Skipping Operation: 'Starting JBoss'"
  else
    # if JBoss is already started no need
    if is_jboss_operational
    then
      echo "JBoss is already running."
      grep -A5 -B1 ERROR $JBOSS_HOME/server/default/log/server.log
      return 0
    fi

    echo "Starting JBOSS"
  	sudo -E $INIT_DIR/jboss start
	  #Waiting JMX service to start
  	sleep 60

  	#Wait for 5 minutes(15*20), check every 15 seconds
	
  	for (( i=1; i<=20; i++ ))
	  do
		  echo "Waiting 15 seconds..."
  		sleep 15
	  	if is_jboss_operational
		  then
            grep -A5 -B1 ERROR $JBOSS_HOME/server/default/log/server.log
  			return 0
	  	fi
  	done
	  exit 1
  fi
}

stop_jboss()
{
  if [ ! -z "$NO_EXEC" ]; then
    info "Skipping Operation: 'Stopping JBoss'"
  else
    if [ is_jboss_started != 0 ];
    then
      echo "Trying to stop JBOSS"
      sudo /etc/init.d/jboss stop

      if is_jboss_started
      then
        echo "Killing JBOSS"
        sudo kill -9 `ps ax|grep jboss|awk '{print $1}'|tr "\n" " "`
      fi
    fi
  fi
}

deploy_annapurna()
{
  if [ ! -z "$NO_EXEC" ]; then
    info "Installing '$HUDSON_JOB'"
  	info "Skipping Operation: Getting '$ANNA_TAR_FILE' from Hudson"
	  info "Skipping Operation: $WGET $ANNA_URL"
	
    info "Skipping Operation: $TAR $BNI_HOME/$ANNA_TAR_FILE -C $BNI_HOME"
    info "Skipping Operation: chmod 755 $JBOSS_HOME/bin/*.sh"
    info "Skipping Operation: chmod 755 $BNI_HOME/*.sh"

    info "Getting Configuration Scripts"
    info "Skipping Operation: rm -f $BNI_CONF_DIR/topology_cluster.xml"
    info "Skipping Operation: ln -s $BNI_DEPLOYED/mnode_topology_cluster.xml $BNI_CONF_DIR/topology_cluster.xml"
  else
    info "Installing '$HUDSON_JOB'"
    info "Getting '$ANNA_TAR_FILE' from Hudson"
    exit_on_error "$WGET $ANNA_URL"
	
    exit_on_error "$TAR $BNI_HOME/$ANNA_TAR_FILE -C $BNI_HOME"
    exit_on_error "chmod 755 $JBOSS_HOME/bin/*.sh"
    exit_on_error "chmod 755 $BNI_HOME/*.sh"

    info "Getting Configuration Scripts"
    rm -f $BNI_CONF_DIR/topology_cluster.xml
    ln -s $BNI_DEPLOYED/mnode_topology_cluster.xml $BNI_CONF_DIR/topology_cluster.xml
  fi
}

update_clustername ()
{
  if [ ! -z "$NO_EXEC" ]; then
    info "Skipping Operation: 'update_clustername'"
    info "Skipping Operation: sed -i 's/clusterName=ana-cluster/clusterName=ana-cluster-SMOKETEST/' $CLUSTER_FILE"
  else
    info "Performing Operation: 'update_clustername'"
    sed -i 's/clusterName="ana-cluster"/clusterName="ana-cluster-SMOKETEST"/' $CLUSTER_FILE
  fi
}

deploy_self()
{
  if [ ! -z "$NO_EXEC" ]; then
    info "Skipping Operation: Deploy Self"
    info "Skipping Operation: ssh $BNI_USER@$SM_IP cd ~;rm -f $0 $FUNCTIONS $ANNA_CONFIGURE_DB $RUNTIME"
    info "Skipping Operation: scp $0 $BNI_USER@$SM_IP:~"
    info "Skipping Operation: scp $FUNCTIONS_SRC_PATH$FUNCTIONS $BNI_USER@$SM_IP:~"
    info "Skipping Operation: scp $FUNCTIONS_SRC_PATH$RUNTIME $BNI_USER@$SM_IP:~"
    info "Skipping Operation: scp $ANNA_CONFIGURE_DB $BNI_USER@$SM_IP:~"
    info "Skipping Operation: ssh $BNI_USER@$SM_IP cd ~;chmod +wx $PROGNAME $FUNCTIONS $RUNTIME $ANNA_CONFIGURE_DB"
    info "Skipping Operation: ssh $BNI_USER@$SM_IP cd ~;./$0 $DEPLOY_ARGS"
  else
    info "deploying self"
    ssh $BNI_USER@$SM_IP "cd ~;rm -f $0 $FUNCTIONS $ANNA_CONFIGURE_DB $RUNTIME"
    scp $0 $BNI_USER@$SM_IP:~
    scp $FUNCTIONS_SRC_PATH$FUNCTIONS $BNI_USER@$SM_IP:~
    scp $FUNCTIONS_SRC_PATH$RUNTIME $BNI_USER@$SM_IP:~
    scp $ANNA_CONFIGURE_DB $BNI_USER@$SM_IP:~
    ssh $BNI_USER@$SM_IP "cd ~;chmod +wx $PROGNAME $FUNCTIONS $RUNTIME $ANNA_CONFIGURE_DB"
    ssh $BNI_USER@$SM_IP "cd ~;./$0 $DEPLOY_ARGS"
  fi
  exit $? 
}

exit_on_error()
{
	COMMAND=$1
	echo ">$COMMAND"
	$COMMAND
	if [ $? -ne 0 ] 
	then 
		exit 1
	fi
}

configure_database()
{
  if [ ! -z "$NO_EXEC" ]; then
    info "Skipping: Configure the Annapurna database (not using -F(orce)..."
    info "Skipping Operation: sudo -E $BNI/bin/configServer.sh $OPT_ARGS solution_name $SM_NAME node_name $SM_NODE_NAME int_ip $SM_NODE_IP msvc_ip $MSVC_IP"
    info "Skipping Operation: sudo -E $BNI_HOME/$ANNA_CONFIGURE_DB $SM_NODE_IP $SIM_IP $MSVC_IP"
  else
    info "Confiure the Annapurna database (not using -F(orce)..."
    sudo -E $BNI/bin/configServer.sh $OPT_ARGS solution_name $SM_NAME node_name $SM_NODE_NAME int_ip $SM_NODE_IP msvc_ip $MSVC_IP || \
      die "Failed configServer.sh could not configure the server"

    # SM_IP needs to be bnisql or sql data won't get injected into database
    # This should be changed in the host file to point to whatever database you are using
    sudo -E $BNI_HOME/$ANNA_CONFIGURE_DB $SM_NODE_IP $SIM_IP $MSVC_IP  || \
      die "Failed $ANNA_CONFIGURE_DB failed to configure the database"

    info "Done."
  fi
}

deploy_anna_pc()
{
  # HACK HACK HACK
  if [ ! -z "$NO_EXEC" ]; then
    info "Skipping Operation: $WGET $ANNA_PC_URL"
    info "Skipping Operation: $TAR $BNI_HOME/$ANNA_PC_TAR_FILE -C $BNI_HOME *.war"
    info "Skipping Operation: $CP $BNI_DEPLOYABLES/*.war $BNI_DEPLOYED"
    info "Skipping Operation: ln -s $BNI_DEPLOYED/dsmcc-s1-protocol-converter-$VERSION.war     $DEPLOY_DIR/dsmcc-s1-protocol-converter-$VERSION.war"
    info "Skipping Operation: ln -s $BNI_DEPLOYED/edge-r6-protocol-converter-$VERSION.war      $DEPLOY_DIR/edge-r6-protocol-converter-$VERSION.war"
    info "Skipping Operation: ln -s $BNI_DEPLOYED/streaming-r2-protocol-converter-$VERSION.war $DEPLOY_DIR/streaming-r2-protocol-converter-$VERSION.war"
  else
    exit_on_error "$WGET $ANNA_PC_URL"
    exit_on_error "$TAR $BNI_HOME/$ANNA_PC_TAR_FILE -C $BNI_HOME *.war"
    exit_on_error "$TAR $BNI_HOME/$ANNA_PC_TAR_FILE -C $BNI_HOME jbossesb/server/default/lib/BNI-beaumaris-jersey-ext-*.jar"
    $CP $BNI_DEPLOYABLES/*.war $BNI_DEPLOYED
    ln -s $BNI_DEPLOYED/dsmcc-s1-protocol-converter-$VERSION.war     $DEPLOY_DIR/dsmcc-s1-protocol-converter-$VERSION.war
    ln -s $BNI_DEPLOYED/edge-r6-protocol-converter-$VERSION.war      $DEPLOY_DIR/edge-r6-protocol-converter-$VERSION.war
    ln -s $BNI_DEPLOYED/streaming-r2-protocol-converter-$VERSION.war $DEPLOY_DIR/streaming-r2-protocol-converter-$VERSION.war
  fi
  # HACK HACK HACK
}

config_udp()
{
  if [ ! -z "$NO_EXEC" ]; then
    info "Skipping Operation: Configuring Ports"
    info "Skipping Operation: /bin/sed -i \"s?\(^.*mcast_port\)\(:\)\(.*$\)\(.*\)?\1:$SS_PORT\}\"?\" $BNI_CONF_DIR/stacks/udp.xml"
  else
    info "Config UDP port $BNI_CONF_DIR/stacks/udp.xml"
    /bin/sed -i "s?\(^.*mcast_port\)\(:\)\(.*$\)\(.*\)?\1:$SS_PORT\}\"?" $BNI_CONF_DIR/stacks/udp.xml
    info "Config UDP port $BNI_CONF_DIR/stacks/topology_udp.xml"
  fi
}


#MAIN

# Remove Old Log
$RM $LOG

# process Optional ARGS
# Process OPTIONS
DBG_OPT=
OPTS_DONE=no
while [ "$#" -gt 0 -a "$OPTS_DONE" = "no" ] ; do
  case "$1" in
  -h|-H|-help|--help)
    print_help
    exit 0
    ;;
  -D)
    DBG_ME=yes
    DEPLOY_ARGS="$DEPLOY_ARGS -D"
    shift
    ;;
  -X)
    NO_EXEC=yes
    DEPLOY_ARGS="$DEPLOY_ARGS -X"
    shift
    ;;
  -deploy)
    DEPLOY=yes
    shift
    ;;
  -jobPrefix)
    shift
    if [ -z "$1" ] ; then
      die "Missing value for -jobPrefix"
    fi
    JOB_PREFIX=$1
    DEPLOY_ARGS="$DEPLOY_ARGS -jobPrefix $1"
    shift
    ;;
  -hq_port)
    shift
    if [ -z "$1" ] ; then
      die "Missing value for -hq_port"
    fi
    HQ_PORT=$1
    DEPLOY_ARGS="$DEPLOY_ARGS -hq_port $1"
    OPT_ARGS="$OPT_ARGS hq_port $1"
    shift
    ;;
  -ss_port)
    shift
    if [ -z "$1" ] ; then
      die "Missing value for -ss_port"
    fi
    SS_PORT=$1
    DEPLOY_ARGS="$DEPLOY_ARGS -ss_port $1"
    OPT_ARGS="$OPT_ARGS ss_port $1"
    shift
    ;;
  *)
    OPTS_DONE=yes
    ;;
  esac
done

# process REQUIRED_ARGS
while [ "$#" -gt 0 ] ; do
  case "$1" in
  -h|--help)
    shift
    print_help
    exit 0
    ;;
  -sm)
    shift
    if [ -z "$1" ] ; then
      die "Missing value for 'sm' IP argument"
    fi
    SM_IP=$1
    DEPLOY_ARGS="$DEPLOY_ARGS -sm $1"
    shift
    ;;
  -sim)
    shift
    if [ -z "$1" ] ; then
      die "Missing value for 'sim' IP argument"
    fi
    SIM_IP=$1
    DEPLOY_ARGS="$DEPLOY_ARGS -sim $1"
    shift
    ;;
  -msvc)
    shift
    if [ -z "$1" ] ; then
      die "Missing value for 'msvc' IP argument"
    fi
    MSVC_IP=$1
    DEPLOY_ARGS="$DEPLOY_ARGS -msvc $1"
    shift
    ;;
  -version)
    shift
    if [ -z "$1" ] ; then
      die "Missing value for '-version' argument"
    fi
    VERSION=$1
    DEPLOY_ARGS="$DEPLOY_ARGS -version $1"
    shift
    ;;
  *)
    info "MAKE SURE OPTIONS ARE SPEIFICED BEFORE REQUIRED ARGS"
    die "Unknown argument '$1'"
    ;;
  esac
done

[ -z "$SM_IP" ] && print_help
[ -z "$SIM_IP" ] && print_help
[ -z "$MSVC_IP" ] && print_help
[ -z "$VERSION" ] && print_help

# deploy the script
if [ ! -z "$DEPLOY" ]; then
  deploy_self
fi


export JBOSS_HOME=$JBOSS_HOME
export JAVA_HOME=/usr/java/default

# DYNAMIC ARGS
#Hudson
HUDSON_ADDR=http://10.10.10.11:8080
HUDSON_BASE_JOB=Annapurna
HUDSON_JOB=$JOB_PREFIX$HUDSON_BASE_JOB

ANNA_TAR_FILE=catv-srm-$VERSION.tar.gz
ANNA_WS_URL=$HUDSON_ADDR/job/$HUDSON_JOB/ws
ANNA_URL=$ANNA_WS_URL/prodbuild/catv-srm/uber-tar/$ANNA_TAR_FILE

ANNA_PC_HUDSON_BASE_JOB=Annapurna-PC
ANNA_PC_HUDSON_JOB=$JOB_PREFIX$ANNA_PC_HUDSON_BASE_JOB
ANNA_PC_TAR_FILE=catv-pc-$VERSION-catv-pc.tar.gz
ANNA_PC_URL=$HUDSON_ADDR/job/$ANNA_PC_HUDSON_JOB/lastSuccessfulBuild/artifact/prodbuild/catv-pc/target/$ANNA_PC_TAR_FILE

stop_jboss
clean
deploy_annapurna
configure_database
update_clustername
config_udp
deploy_anna_pc
start_jboss

